package com.qingmu.club.minaapi.controller.club;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingmu.club.minaapi.custom.logic.LearnDiaryLogic;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.enums.ClubUsersTypeEnum;
import com.qingmu.club.minaapi.enums.MemberTypeEnum;
import com.qingmu.club.minaapi.enums.UserClassHoursStatusEnum;
import com.qingmu.club.minaapi.model.QueryLearnDiaryModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.FontUtil;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 粉丝排行 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 **/

@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "会员中心(俱乐部端小程序)", description = "会员中心(俱乐部端小程序)")
@RequestMapping("/club/member")
public class ClubMemberController {


    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubService clubService;

    @Autowired
    LearnDiaryLogic learnDiaryLogic;

    @Autowired
    ClubStaffService clubStaffService;

    @Autowired
    LearnDiaryService learnDiaryService;

    @Autowired
    LearnDiaryReplyService learnDiaryReplyService;

    @Autowired
    CourseClasshourService courseClasshourService;

    @Autowired
    ClubUsersClasshoursService clubUsersClasshoursService;

    @Autowired
    UsersWxLogic usersWxLogic;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    ClubUsersCourseService clubUsersCourseService;

    @RequestMapping(value = "/report", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "举报")
    public ResponseEntity report(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "日记id") @RequestParam(required = true) String learnDiaryId,
            @ApiParam(required = true, value = "内容") @RequestParam(required = true) String content
    ) {


        return ResponseObject.success();

    }

    @RequestMapping(value = "/pinOrRepeal", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "销课")
    public ResponseEntity pinClass(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员课时ID") @RequestParam(required = true) String memberClasshoursId,
            //@ApiParam(required = true, value = "PIN销课 REPEAL撤销") @RequestParam(required = true) UserClassHoursStatusEnum hoursStatus,
            @ApiParam(required = true, value = "上课时间") @RequestParam(required = true) String attendTime
    ) {
        ClubStaff clubStaff = this.usersWxLogic.getClubStaff(staffId);
        if (clubStaff == null) {
            return ResponseObject.error(401, "人员信息找不到");
        }
        ClubUsersClasshours clubUsersClasshours = this.clubUsersClasshoursService.getById(memberClasshoursId);
        if (clubUsersClasshours == null) {
            return ResponseObject.error(601, "会员课时不存在");
        }

        QueryWrapper<ClubUsersCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsersCourse.COURSE_ID,clubUsersClasshours.getCourseId()).eq(ClubUsersCourse.CLUB_USERS_ID,clubUsersClasshours.getClubUsersId());
        ClubUsersCourse clubUsersCourse = this.clubUsersCourseService.getOne(queryWrapper);

        ClubUsers clubUsers = this.clubUsersService.getById(clubUsersClasshours.getClubUsersId());
        Integer remainHoursNum = 0;
        String[] date = attendTime.split(" ");


        QueryWrapper<LearnDiary> qw = new QueryWrapper<>();
        qw.eq("date_format(diary_time,'%Y-%m-%d')", date[0]);
        qw.lambda().eq(LearnDiary::getAuthorId, staffId).eq(LearnDiary::getUserId, clubUsersClasshours.getClubUsersId());
        List<LearnDiary> learnDiaryList = this.learnDiaryService.list(qw);
        if (CollectionUtils.isEmpty(learnDiaryList)) {
            return ResponseObject.error(602, date[0] + " 未发布学员学习日记，请先补发当日学习日记再进行销课");
        }

        clubUsersClasshours.setAttendTime(attendTime);
        clubUsersClasshours.setAttendCoach(staffId);
        clubUsersClasshours.setAttendCoachName(clubStaff.getStaffName());
        clubUsersClasshours.setStatus(KeyValueDefine.HAS_BEEN_LEARNING);
        if(clubUsers.getBuyCourseId().equals(clubUsersClasshours.getCourseId())) {
            remainHoursNum = clubUsers.getRemainHours() - 1;
            clubUsers.setRemainHours(remainHoursNum); //已学课时
            if(remainHoursNum==0){
                clubUsersCourse.setStatus(0);
                clubUsersCourse.setType(1);
                clubUsers.setUserShowStatus("before");//历史学员
            }
        }
        boolean state0 = this.clubUsersCourseService.updateById(clubUsersCourse);

        boolean state = this.clubUsersClasshoursService.updateById(clubUsersClasshours);
        if (!state || !state0) {
            return ResponseObject.error();
        }


        if (StringUtils.isEmpty(clubUsers.getAttendCoach())) {  //给一个默认的上课人员
            clubUsers.setAttendCoach(staffId);
            clubUsers.setAttendCoachName(clubStaff.getStaffName());
        }
        boolean state2 = this.clubUsersService.updateById(clubUsers);
        if (!state2) {
            return ResponseObject.error();
        }
        ClubUsersClasshours result = clubUsersClasshoursService.getById(clubUsersClasshours.getId());
        return ResponseObject.success(result);
    }

    @RequestMapping(value = "/queryMemberById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询会员详情")
    public ResponseEntity queryMemberById(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String userId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        ClubUsers clubUsers = this.clubUsersService.getById(userId);
        if (clubUsers == null) {
            return ResponseObject.error(601, "无此会员");
        }
        return ResponseObject.success(clubUsers);
    }


    @RequestMapping(value = "/queryMemberClassHoursList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询会员课时")
    public ResponseEntity queryClubUsersClassHoursList(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String userId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }
        ClubUsers clubUsers = this.clubUsersService.getById(userId);
        if (clubUsers == null) {
            return ResponseObject.error(601, "无此会员");
        }


        QueryWrapper<ClubUsersClasshours> qw = new QueryWrapper<>();
        qw.lambda().eq(ClubUsersClasshours::getClubUsersId,userId).eq(ClubUsersClasshours::getStatus,0).eq(ClubUsersClasshours::getCourseId,clubUsers.getBuyCourseId());
        List<ClubUsersClasshours> noFinishLearnList = this.clubUsersClasshoursService.list(qw);

        QueryWrapper<ClubUsersClasshours> qws = new QueryWrapper<>();
        qws.lambda().eq(ClubUsersClasshours::getClubUsersId,userId).eq(ClubUsersClasshours::getStatus,1).eq(ClubUsersClasshours::getCourseId,clubUsers.getBuyCourseId());
        List<ClubUsersClasshours> finishLearnList = this.clubUsersClasshoursService.list(qws);

        HashMap<String,Object> map = new HashMap<>();
        map.put("noFinishLearnList",noFinishLearnList);
        map.put("finishLearnList",finishLearnList);
        return ResponseObject.success(map);
    }

    @RequestMapping(value = "/queryMember", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "会员中心列表")
    public ResponseEntity list(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "会员类型") @RequestParam(required = true) MemberTypeEnum memberType,
            @ApiParam(required = false, value = "当前页", example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(required = false, value = "每页数量", example = "10") @RequestParam(required = false) Integer pageSize,
            @ApiParam(required = false, value = "会员名称") @RequestParam(required = false) String userName
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }
        if(page==null){
            page=0;
        }
        if(pageSize==null){
            pageSize=10;
        }

        ClubShop clubShop = this.clubShopService.getById(shopId);
        if(clubShop==null){
            return ResponseObject.error(556,"门店不存在");
        }

        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(ClubUsers.SHOP_ID,shopId)
                .eq(memberType.equals(MemberTypeEnum.COURSE_MEMBER),ClubUsers.USER_SHOW_STATUS, KeyValueDefine.ONLINE)  //在读学员
                .like(!StringUtils.isEmpty(userName),ClubUsers.USER_NAME,userName);
        IPage<ClubUsers> iPage= this.clubUsersService.page(new Page<>(page,pageSize),queryWrapper);
        return ResponseObject.successWithIpage(iPage);
    }

    @RequestMapping(value = "/queryMemberLearnDiary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询会员学习日记")
    public ResponseEntity learnDiaryList(
            @ApiParam(required = true, value = "俱乐部人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "当前页",example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(required = false, value = "每页数量",example = "10") @RequestParam(required = false) Integer pageSize

    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        ClubUsers clubUsers = this.clubUsersService.getById(userId);
        if(clubUsers==null){
            return ResponseObject.error(601,"会员找不到");
        }


        if(page==null){
            page=0;
        }
        if(pageSize==null){
            pageSize=10;
        }

        QueryWrapper<LearnDiary> qw = new QueryWrapper<>();
        qw.eq(LearnDiary.USER_ID,userId).orderByDesc(LearnDiary.CREATE_TIME).eq(LearnDiary.STATUS,KeyValueDefine.ONLINE_STATUS);
        IPage<LearnDiary> iPage = learnDiaryService.page(new Page<>(page,pageSize),qw);
        List<LearnDiary> learnDiaryList = iPage.getRecords();

        List<QueryLearnDiaryModel> results = new ArrayList();

        for(LearnDiary learnDiary :learnDiaryList){
            boolean remove = false;
            if(learnDiary.getAuthorId().equals(staffId)){//查询出自己发的学习日记 标记是否可删除
                remove=true;
            }
            QueryLearnDiaryModel item = new QueryLearnDiaryModel();
            BeanUtils.copyProperties(learnDiary, item);
            item.setRemove(remove);

            QueryWrapper<LearnDiaryReply> replyQueryWrapper = new QueryWrapper<>();
            replyQueryWrapper.eq(LearnDiaryReply.LEARN_DIARY_ID,learnDiary.getId()).eq(LearnDiaryReply.STATUS,KeyValueDefine.ONLINE_STATUS);
            List<LearnDiaryReply> replyList = this.learnDiaryReplyService.list(replyQueryWrapper);

            item.setReplyList(replyList);
            results.add(item);
        }
        return ResponseObject.successWithIpageObject(iPage,results);
    }


    @RequestMapping(value = "/coachAddLearnDiary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "人员发布学习日记")
    public ResponseEntity addLearnDiary(
            @ApiParam(required = true, value = "俱乐部人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "日记内容") @RequestParam(required = false) String content,
            @ApiParam(required = false, value = "发布时间") @RequestParam(required = false) Date diaryTime,
            @ApiParam(required = false, value = "图片") @RequestParam(required = false) String imageUrl,
            @ApiParam(required = false, value = "视频") @RequestParam(required = false) String videoUrl,
            @ApiParam(required = true, value = "人员身份") @RequestParam(required = true) String staffTag
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        if(StringUtils.isEmpty(content) && StringUtils.isEmpty(imageUrl) && StringUtils.isEmpty(videoUrl)){
            return ResponseObject.error(552,"请输入内容");
        }
        try {

            boolean state = FontUtil.fontIllegal(content.trim());

            if(!state){
                return ResponseObject.error(552,"您输入的内容存在违规，请重新输入!");
            }
        }catch (Exception e){
            return ResponseObject.error();
        }


        String tag ="" ;//  * 人员角色0-教练1-课程顾问2-店主3-管理员
        Integer authorType = 0 ;
        if(staffTag.equals(KeyValueDefine.COACH)){
            tag="(教练）";
            authorType = 0 ;
        }else if(staffTag.equals(KeyValueDefine.COUNSELOR)){
            tag="(课程顾问）";
            authorType = 1 ;
        }else if(staffTag.equals(KeyValueDefine.SHOPOWNER)){
            tag="(店长)";
            authorType = 2 ;
        }else {
            tag="(管理员)";
            authorType = 3 ;
        }

        LearnDiary ld = new LearnDiary();
        ld.setAuthorId(staffId);
        ld.setUserId(userId);
        ld.setContent(content);
        ld.setImageUrl(imageUrl);
        ld.setVideoUrl(videoUrl);
        ld.setAuthorName(clubStaff.getStaffName()+tag);
        ld.setAuthorIcon(clubStaff.getAvatar());
        ld.setAuthorType(authorType);
        //ld.setStatus(0);
        ld.setStatus(1);
        if(diaryTime!=null){
            ld.setDiaryTime(diaryTime);
        }else{
            ld.setDiaryTime(new Date());
        }
        boolean state = this.learnDiaryService.save(ld);
        if(!state){
            return ResponseObject.error(553,"发布失败");
        }
        //return ResponseObject.error(601,"发布成功，待审核通过后即可显示"); //待审核通过后 返回200
        return ResponseObject.success();
    }

    @RequestMapping(value = "/removeDiaryById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除日记")
    public ResponseEntity removeById(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "日记id") @RequestParam(required = true) String learnDiaryId
    ) {

        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        LearnDiary learnDiary = learnDiaryService.getById(learnDiaryId);

        if(learnDiary==null){
            return ResponseObject.error(601,"日记信息找不到");
        }
        boolean state = learnDiaryService.removeById(learnDiaryId);
        if(!state){
            return ResponseObject.error(553,"删除失败");
        }
        return ResponseObject.success();
    }

    @RequestMapping(value = "/commentDiary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "评论日记")
    public ResponseEntity commentDiary(
            @ApiParam(required = true, value = "评论人id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "日记id") @RequestParam(required = true) String diaryId,
            @ApiParam(required = true, value = "评论内容") @RequestParam(required = true) String content
    ) {

        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }


        LearnDiary learnDiary = learnDiaryService.getById(diaryId);
        if(learnDiary==null){
            return ResponseObject.error(601,"日记信息找不到");
        }

        try {

            boolean state = FontUtil.fontIllegal(content.trim());
            if(!state){
                return ResponseObject.error(552,"您输入的内容存在违规，请重新输入!");
            }
        }catch (Exception e){
            return ResponseObject.error();
        }


        LearnDiaryReply ldr = new LearnDiaryReply();
        ldr.setLearnDiaryId(diaryId);
        ldr.setReplierId(staffId);
        ldr.setReplierContent(content);
        ldr.setReplierIcon(clubStaff.getAvatar());
        ldr.setReplierName(clubStaff.getStaffName()+"(教练)");
        ldr.setStatus(KeyValueDefine.ONLINE_STATUS);

        boolean state = learnDiaryReplyService.save(ldr);
        if(!state){
            return ResponseObject.error();
        }
        //return ResponseObject.success(this.learnDiaryReplyService.getById(ldr.getId()));
        //return ResponseObject.error(601,"发布成功，待审核通过后即可显示"); //待审核通过后 返回200
        return ResponseObject.success();
    }


    @RequestMapping(value = "/removeReplyById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除回复")
    public ResponseEntity removeReplyById(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "回复id") @RequestParam(required = true) String replyId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }
        LearnDiaryReply learnDiaryReply = learnDiaryReplyService.getById(replyId);

        if(learnDiaryReply==null){
            return ResponseObject.error(601,"日记信息找不到");
        }
        boolean state = learnDiaryReplyService.removeById(replyId);
        if(!state){
            return ResponseObject.error(553,"删除失败");
        }
        return ResponseObject.success();
    }

    @RequestMapping(value = "/replyComment", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "回复评论")
    public ResponseEntity replyComment(
            @ApiParam(required = true, value = "回复人id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "评论id") @RequestParam(required = true) String replyId,
            @ApiParam(required = true, value = "回复内容") @RequestParam(required = true) String content
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }
        LearnDiaryReply learnDiaryReply = learnDiaryReplyService.getById(replyId);

        if (learnDiaryReply == null) {
            return ResponseObject.error(601, "评论信息找不到");
        }

        try {
            boolean state = FontUtil.fontIllegal(content.trim());
            if(!state){
                return ResponseObject.error(552,"您输入的内容存在违规，请重新输入!");
            }
        }catch (Exception e){
            return ResponseObject.error();
        }

        LearnDiaryReply ldr = new LearnDiaryReply();

        ldr.setByReply(learnDiaryReply.getReplierName());
        ldr.setByReplyId(learnDiaryReply.getReplierId());
        ldr.setLearnDiaryId(learnDiaryReply.getLearnDiaryId());
        ldr.setParentId(replyId); //父级

        ldr.setReplierId(staffId);
        ldr.setReplierContent(content);
        ldr.setReplierIcon(clubStaff.getAvatar());
        ldr.setReplierName(clubStaff.getStaffName()+"(教练)");
        ldr.setStatus(KeyValueDefine.ONLINE_STATUS);

        boolean state = learnDiaryReplyService.save(ldr);
        if (!state) {
            return ResponseObject.error();
        }
        //return ResponseObject.success(this.learnDiaryReplyService.getById(ldr.getId()));
        //return ResponseObject.error(601,"发布成功，待审核通过后即可显示"); //待审核通过后 返回200
        return ResponseObject.success();
    }

}
